import UserSaveOrUpdateModal, {UserCreateOrUpdateInfo,} from '@/pages/family-counselor/user-newOrUpdate-modal';
import {
  deleteUser,
  FamilyInfo,
  FamilyListReqParam,
  getFamilyList,
  queryUseList,
  resetPassword,
  UserPageReq
} from '@/services/family/api';
import {PlusOutlined} from '@ant-design/icons';
import {ActionType, PageContainer, ProColumnType, ProTable} from '@ant-design/pro-components';
import {Button, message, Modal} from 'antd';
import to from 'await-to-js';
import React, {useLayoutEffect, useRef, useState} from 'react';
import {UserInfo} from "@/common/user";

const UserList: React.FC = () => {
  const [currentModalUserInfo, setCurrentModalUserInfo] = useState<UserCreateOrUpdateInfo>({},);
  const [userSaveOrUpdateModalVisible, setUserSaveOrUpdateModalVisible] = useState<boolean>(false);
  const [familyList, setFamilyList] = useState<FamilyInfo[]>([]);

  const params = {
    current: 1,
    pageSize: 50,
  };

  const handleQueryFamilyList = async (params: FamilyListReqParam): Promise<any> => {
    const [err, res] = await to(getFamilyList(params));
    if(err) {
      return message.error({
        content: err?.message || '家庭列表获取失败',
      });
    }
    setFamilyList(res?.result);
  };
  useLayoutEffect( () => {
    handleQueryFamilyList({})
  }, [1]);

  const proTableRef = useRef<ActionType>();
  const showUserInfoModal = (userInfo: UserCreateOrUpdateInfo) => {
    setCurrentModalUserInfo(userInfo);
    setUserSaveOrUpdateModalVisible(true);
  };

  const handleUserResetPwd = async (userInfo: UserInfo) => {
    const [err,res] = await to(resetPassword(userInfo.id));
    if(err) {
      return message.error("密码重置失败: " + err.message);
    }
    return message.success(`用户${userInfo.name}的密码重置为${res?.result}`);
  }

  const handleDeleteUser = async (userId: number) => {
    const [err,res] = await to(deleteUser(userId));
    if(err || !res?.result) {
      return message.error("用户删除失败: " + err?.message);
    }
    proTableRef?.current?.reload();
    return message.success(`用户删除成功`);
  }

  const columns: ProColumnType<UserInfo>[] = [
    {
      title: '用户ID',
      dataIndex: 'id',
      key: 'id',
      hideInSearch: true,
    },
    {
      title: '用户名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '用户所属家庭',
      dataIndex: 'activeFamilyId',
      key: 'activeFamilyId',
      valueType: 'select',
      fieldProps: {
        showSearch: true,
        options: familyList?.map((item) => ({
          label: item.code + ": " + item.name,
          value: item.id,
        })),
      },
      // proFieldProps: {
      //   allowClear: true,
      //   allowSearch: true,
      // },
      render(_text, record) {
        const {activeFamilyId, activeFamilyName, activeFamilyCode} = record;
        if(!activeFamilyId) {
          return <span>-</span>;
        }
        return <span>{activeFamilyName}&nbsp;({activeFamilyCode})</span>;
      },
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      valueType: "select",
      search: true,
      fieldProps: {
        showSearch: true,
      },
      valueEnum: {
        "爸爸": "爸爸",
        "妈妈": "妈妈",
        "哥哥": "哥哥",
        "弟弟": "弟弟",
        "姐姐": "姐姐",
        "妹妹": "妹妹",
        "爷爷": "爷爷",
        "奶奶": "奶奶",
        "老师": "老师",
      },
    },
    {
      hideInSearch: true,
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'id',
    },
    {
      hideInSearch: true,
      title: '操作',
      dataIndex: 'lastReportTime',
      key: 'lastReportTime',
      render(_text, record): React.JSX.Element {
        return (
          <>
            <Button
              size="small"
              type="primary"
              onClick={() => {
                showUserInfoModal({
                  id: record.id,
                  name: record.name,
                  activeFamilyId: record.activeFamilyId,
                  role: record.role,
                });
              }}
            >
              编辑用户
            </Button>
            {/*&nbsp;*/}
            {/*<Button*/}
            {/*  size="small"*/}
            {/*  type="primary"*/}
            {/*  onClick={() => {*/}
            {/*    Modal.confirm({*/}
            {/*      title: `确定要重置用户${record.name}的密码吗？`,*/}
            {/*      okText: '确定',*/}
            {/*      cancelText: '取消',*/}
            {/*      onOk() {*/}
            {/*        handleUserResetPwd(record)*/}
            {/*      },*/}
            {/*    })*/}
            {/*  }}*/}
            {/*>*/}
            {/*  重置密码*/}
            {/*</Button>*/}
            &nbsp;
            <Button
              size="small"
              variant="solid"
              color="danger"
              onClick={() => {
                Modal.confirm({
                  title: `删除用户${record.name}的操作是不可逆的，确认执行吗？`,
                  okText: '确定',
                  cancelText: '取消',
                  onOk() {
                    handleDeleteUser(record.id)
                  },
                })
              }}
            >
              删除用户
            </Button>
          </>
        );
      },
    },
  ];

  return (
    <PageContainer
      header={{
        title: null,
      }}
    >
      <ProTable
        defaultSize="small"
        actionRef={proTableRef}
        rowKey={'id'}
        columns={columns}
        // params 是需要自带的参数
        // 这个参数优先级更高，会覆盖查询表单的参数
        params={params}
        // 第一个参数 params 查询表单和 params 参数的结合
        // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
        request={async (
          // 第一个参数 params 查询表单和 params 参数的结合
          // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
          params: UserPageReq,
        ) => {
          // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
          // 如果需要转化参数可以在这里进行修改
          const [err, baseResponse] = await to(queryUseList(params));
          if (err || baseResponse?.code !== '0') {
            return { data: [], success: false };
          }
          return {
            total: baseResponse?.result.length,
            data: baseResponse?.result,
            success: true,
          };
        }}
        search={{
          searchText: '搜索',
          labelWidth: 'auto',
          collapsed: false,
          span: 6,
        }}
        debounceTime={100}
        toolBarRender={() => [
          <Button
            size="small"
            key="3"
            type="primary"
            onClick={() => {
              showUserInfoModal({});
            }}
          >
            <PlusOutlined />
            新建用户
          </Button>,
        ]}
      />

      <UserSaveOrUpdateModal
        onOpenChange={setUserSaveOrUpdateModalVisible}
        userInfo={currentModalUserInfo}
        modalVisible={userSaveOrUpdateModalVisible}
        onSubmit={(userInfo: UserCreateOrUpdateInfo) => {
          console.log(userInfo);
          if(currentModalUserInfo.id) {
            // @ts-ignore 刷新家庭列表
            proTableRef?.current?.reloadAndRest();
            return;
          }
          // @ts-ignore 刷新家庭列表
          proTableRef?.current?.reload();
        }}
      />
    </PageContainer>
  );
};

export default UserList;
